package com.ucode.hrm.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ucode.hrm.mapper.HrmCustomerProjectMapper;
import com.ucode.hrm.service.HrmCustomerProjectService;
import com.ucode.model.hrm.HrmCustomerProject;
import com.ucode.model.hrm.enums.HrmSysResultCodeEnum;
import com.ucode.tool.base.enums.GlobalResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.IdentifyUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Collection;

@Service
public class HrmCustomerProjectServiceImpl implements HrmCustomerProjectService {

    @Resource
    private HrmCustomerProjectMapper hrmCustomerProjectMapper;

    @Override
    public HrmCustomerProjectMapper initMapper() {
        return hrmCustomerProjectMapper;
    }

    @Override
    public Long insert(HrmCustomerProject hrmCustomerProject) {

        if(ObjUtil.isNull(hrmCustomerProject.getId()))
            hrmCustomerProject.setId(IdentifyUtils.getDefaultSnowflakeId());

        this.validateForCreateOrUpdate(true, hrmCustomerProject);
        int i = hrmCustomerProjectMapper.insert(hrmCustomerProject);

        return i > 0 ? hrmCustomerProject.getId() : null;
    }

    @Override
    public int update(HrmCustomerProject hrmCustomerProject) {
        this.validateForCreateOrUpdate(false, hrmCustomerProject);
        return hrmCustomerProjectMapper.update(hrmCustomerProject);
    }

    @Override
    public int updateStatus(Collection<Long> ids, Integer status) {
        return hrmCustomerProjectMapper.updateStatus(ids, status);
    }

    /**
     * 验证数据
     * @param isInsert 是否新增
     * @param bean
     */
    private void validateForCreateOrUpdate(boolean isInsert, HrmCustomerProject bean) {
        boolean is_validate_name = true;//是否需要验证名称的唯一性
        if(!isInsert){
            if(ObjectUtil.isNull(bean.getId()))
                throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
            HrmCustomerProject db_bean = this.selectByPrimaryKey(bean.getId());
            if(ObjectUtil.isNull(db_bean))
                throw new UcodeServiceException(HrmSysResultCodeEnum.CUSTOMER_COMPANY_NOT_EXISTS);

            //如果跟数据库一致，代表无需验证
            is_validate_name = (ObjectUtil.isNotNull(bean.getProjectName()) && !bean.getProjectName().equals(db_bean.getProjectName()))
                    || (ObjectUtil.isNotNull(bean.getCustomerCompanyId()) && !bean.getCustomerCompanyId().equals(db_bean.getCustomerCompanyId()));
        }

        if(is_validate_name && ObjectUtil.isNotNull(this.queryOneByName(bean.getCustomerCompanyId(),bean.getProjectName()))){
            // 校验名称的唯一性
            throw new UcodeServiceException(HrmSysResultCodeEnum.CUSTOMER_PROJECT_NAME_DUPLICATE);
        }

    }

}
